package com.lhgray.sglhome.presentation.viewModel

import android.net.Uri
import androidx.lifecycle.viewModelScope
import com.freightoa.foundation.viewmodel.BaseState
import com.freightoa.foundation.viewmodel.BaseViewModel
import com.freightoa.foundation.viewmodel.UiIntent
import com.lhgray.sglhome.domain.usecase.MyAccountUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 我的页面
 */

sealed interface MyAccountState : BaseState {
    data object Idle : MyAccountState
    data object Loading : MyAccountState
    data class Success(val message: String) : MyAccountState
    data class Error(val errorMessage: String) : MyAccountState
}

sealed interface MyAccountIntent : UiIntent {
    data class MyAccount(val list: MutableList<Uri>) : MyAccountIntent
}

@HiltViewModel
class MyAccountViewModel @Inject constructor(private val myAccountUseCase: MyAccountUseCase) :
    BaseViewModel<MyAccountState, MyAccountIntent>() {

    private val _uiStateFlow = MutableStateFlow<MyAccountState>(MyAccountState.Idle)
    override val uiState: StateFlow<MyAccountState> = _uiStateFlow.asStateFlow()
    override fun handleIntent(intent: MyAccountIntent) {
        viewModelScope.launch {
            when (intent) {
                is MyAccountIntent.MyAccount -> {
                    _uiStateFlow.value = MyAccountState.Loading
                    val result = myAccountUseCase(intent.list)
                    if (result) {
                        _uiStateFlow.value = MyAccountState.Success("登录成功")
                    } else {
                        _uiStateFlow.value = MyAccountState.Error("用户名或密码错误")
                    }
                }
            }
        }
    }
}